<script setup>


import { onMounted, ref } from 'vue'
import XYZ from 'ol/source/XYZ'
import { fromLonLat } from 'ol/proj'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import { Feature } from 'ol'
import { Vector } from 'ol/layer'
import VectorLayer from 'ol/layer/Vector'
import { LineString } from 'ol/geom'
import Map from 'ol/Map'
import { Stroke, Style } from 'ol/style'
import VectorSource from 'ol/source/Vector'

const mapRef = ref(null)
const mapInstance = ref(null)
const center = [113.267252, 23.137949]
const mapView = ref(new View({
  center: center,
  zoom: 10,
  projection: 'EPSG:4326'
}))
const gaodeLayer = new TileLayer({
  source: new XYZ({
    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
    crossOrigin: 'anonymous'
  })
})
const lineFeature = new Feature({
  geometry: new LineString([[114.25,30.59],[116.46,39.92]])

})
lineFeature.setStyle(new Style({
  stroke: new Stroke({
    color: 'black',
  })
}))
const vectorSource = new VectorSource({
  features: [lineFeature],
})
const lineLayer = new VectorLayer({
  source: vectorSource,
})
const lineArr = ref([])
onMounted(() => {
  mapInstance.value = new Map({
    target: mapRef.value,
    view: mapView.value,
    layers: [gaodeLayer,lineLayer]
  })
  mapInstance.value.on('click',e => {
    vectorSource.clear()
    const coordinate = e.coordinate;
    lineArr.value.push(coordinate)
    if (lineArr.value.length === 2) {
      let lineFeature = new Feature({
        geometry: new LineString(lineArr.value),
      })
      lineFeature.setStyle(new Style({
        stroke: new Stroke({
          color:'lighted',
          width: 3
        })
      }))
      vectorSource.addFeature(lineFeature)
      lineArr.value = []
    }
  })
})
</script>

<template>
<div id="map-container">
  <div id="map" ref="mapRef"></div>
</div>
</template>

<style scoped>
#map-container{
  width:100vw;
  height:100vh;
  box-sizing: border-box;
}
#map{
  width:100%;
  height:100%;
}

</style>
